<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon book-icon">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">图书总数</div>
              <div class="stat-value">{{ stats.bookCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon category-icon">
              <el-icon><Files /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">分类总数</div>
              <div class="stat-value">{{ stats.categoryCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon borrow-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">出版社总数</div>
              <div class="stat-value">{{ stats.publisherCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="stat-card-content">
            <div class="stat-icon user-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-title">用户总数</div>
              <div class="stat-value">{{ stats.userCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近添加的图书 -->
    <el-card class="recent-books-card">
      <template #header>
        <div class="card-header">
          <span>最近添加的图书</span>
          <el-button type="primary" size="small" @click="$router.push('/book')">查看全部</el-button>
        </div>
      </template>
      <el-table :data="recentBooks" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="图书名称" min-width="180" />
        <el-table-column prop="author" label="作者" min-width="120" />
        <el-table-column prop="publisher" label="出版社" min-width="150" />
        <el-table-column prop="isbn" label="ISBN" min-width="120" />
        <el-table-column prop="categoryName" label="分类" min-width="100" />
        <el-table-column prop="stock" label="库存" width="80" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="$router.push(`/book/edit/${scope.row.id}`)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 添加分页组件 -->
      <el-pagination
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination-container"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getBookList } from '../api/book'
import { getAllCategories } from '../api/category'
import { getAllStatistics } from '../api/statistics'
// 统计数据
const stats = ref({
  bookCount: 0,
  categoryCount: 0,
  publisherCount: 0,
  userCount: 0
})

// 最近添加的图书
const recentBooks = ref([])
const loading = ref(false)
const total = ref(0) // 添加总数变量

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 5,
  sortField: 'createTime',
  sortOrder: 'desc'
})

// 分类选项
const categoryOptions = ref([])

// 获取所有分类
const fetchCategories = async () => {
  try {
    const res = await getAllCategories()
    if (res.data) {
      categoryOptions.value = res.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取最近添加的图书
const fetchRecentBooks = async () => {
  loading.value = true
  try {
    const res = await getBookList({
      current: queryParams.current,
      size: queryParams.size,
      sortField: queryParams.sortField,
      sortOrder: queryParams.sortOrder
    })
    
    if (res.code === 200 && res.data) {
      // 确保records是数组
      if (Array.isArray(res.data.records)) {
        // 使用后端返回的已分页数据
        recentBooks.value = res.data.records
        
        // 处理total值，确保分页正确工作
        if (res.data.total !== undefined && res.data.total > 0) {
          // 如果后端返回了有效的total值，直接使用
          total.value = res.data.total;
        } else if (res.data.records.length > 0) {
          // 如果后端没有返回total但有数据，使用固定估计值
          // 这里使用一个固定的估计值，避免每次导航回来时累加计算
          const recordsLength = res.data.records.length;
          
          // 如果当前页记录数小于页大小，可能是最后一页
          // 直接使用实际记录数作为total，避免错误估计
          total.value = recordsLength;
          
          // 如果是第一页且记录数等于页大小，可能还有更多数据，但不进行估计
          // 这样确保显示的总数不会超过实际数量
        }
        
        // 更新图书总数统计
        stats.value.bookCount = total.value;
      } else {
        // 没有数据时重置为0
        recentBooks.value = [];
        total.value = 0;
      }
    } else {
      recentBooks.value = [];
      total.value = 0;
    }
    
    // 处理分类名称
    if (recentBooks.value.length > 0) {
      recentBooks.value.forEach(book => {
        const category = categoryOptions.value.find(c => c.id === book.categoryId)
        book.categoryName = category ? category.name : '未分类'
      })
    }
  } catch (error) {
    console.error('获取最近图书失败:', error)
    recentBooks.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页大小改变事件
const handleSizeChange = (size) => {
  queryParams.size = size
  fetchRecentBooks()
}

// 页码改变事件
const handleCurrentChange = (current) => {
  queryParams.current = current
  fetchRecentBooks()
}

// 模拟获取统计数据
// const fetchStats = () => {
//   // 这里应该调用后端API获取真实数据
//   // 目前使用模拟数据
//   stats.value = {
//     bookCount: 0, // 会被fetchRecentBooks更新
//     categoryCount: 8,
//     publisherCount: 25,
//     userCount: 12
//   }
// }

// 获取统计数据
const fetchStats = async () => {
  try {
    const res = await getAllStatistics()
    if (res.code === 200 && res.data) {
      stats.value = {
        bookCount: res.data.bookCount || 0,
        categoryCount: res.data.categoryCount || 0,
        publisherCount: res.data.publisherCount || 0,
        userCount: res.data.userCount || 0
      }
    } else {
      stats.value = { bookCount: 0, categoryCount: 0, publisherCount: 0, userCount: 0 }
    }
  } catch (e) {
    console.error('获取统计数据失败:', e)
    stats.value = { bookCount: 0, categoryCount: 0, publisherCount: 0, userCount: 0 }
  }
}

onMounted(() => {
  fetchStats()
  fetchCategories()
  fetchRecentBooks()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.stat-card {
  margin-bottom: 20px;
  height: 120px;
}

.stat-card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 30px;
  color: white;
}

.book-icon {
  background-color: #409EFF;
}

.category-icon {
  background-color: #67C23A;
}

.borrow-icon {
  background-color: #E6A23C;
}

.user-icon {
  background-color: #F56C6C;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.recent-books-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>